package org.ohos.rajawali3d.examples.utils;

import ohos.app.Context;
import ohos.security.SystemPermission;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import static ohos.bundle.IBundleManager.PERMISSION_GRANTED;

public class PermissionHelper {
    public static final int PERMISSION_REQUEST_CODE = 1;
    private static PermissionHelper permissionHelper;
    private final List<PermissionCallback> permissionCallbacks = new ArrayList<>();

    private final Context context;
    private final List<String> permissions = new LinkedList<>(Arrays.asList(
            SystemPermission.READ_MEDIA,
            SystemPermission.WRITE_MEDIA,
            SystemPermission.CAMERA,
            SystemPermission.INTERNET,
            SystemPermission.GET_NETWORK_INFO,
            SystemPermission.GET_WIFI_INFO,
            SystemPermission.RESET_BIOMETRIC_LOCKOUT,
            SystemPermission.RUNNING_LOCK,
            SystemPermission.NFC_CARD_EMULATION,
            SystemPermission.NFC_TAG,
            SystemPermission.RCV_NFC_TRANSACTION_EVENT,
            SystemPermission.VIBRATE,
            SystemPermission.ACCELEROMETER,
            SystemPermission.READ_USER_STORAGE,
            SystemPermission.WRITE_USER_STORAGE
    ));

    private PermissionHelper(Context context) {
        this.context = context;
    }

    public static void init(Context context) {
        permissionHelper = new PermissionHelper(context);
    }

    public static PermissionHelper getInstance() {
        return permissionHelper;
    }

    public boolean hasPermission() {
        if (context == null) {
            return false;
        }
        permissions.removeIf(ss -> context.verifySelfPermission(ss) == PERMISSION_GRANTED);
        return permissions.isEmpty();
    }

    public void addPermissionCallback(PermissionCallback callback) {
        if (callback == null) {
            return;
        }
        permissionCallbacks.add(callback);
    }

    public void requestPermissions() {
        permissions.removeIf(
                permission -> context.verifySelfPermission(permission) == PERMISSION_GRANTED || !context.canRequestPermission(permission));
        if (!permissions.isEmpty()) {
            context.requestPermissionsFromUser(permissions.toArray(new String[0]), PERMISSION_REQUEST_CODE);
        }
    }

    public void onPermissionGranted() {
        for (PermissionCallback callback : permissionCallbacks) {
            callback.onPermissionGranted();
        }
    }

    public void onPermissionDenied() {
        for (PermissionCallback callback : permissionCallbacks) {
            callback.onPermissionDenied();
        }
    }

    public interface PermissionCallback {
        void onPermissionGranted();

        void onPermissionDenied();
    }
}
